from django.shortcuts import render,redirect,HttpResponse
from web import models
from django.http import JsonResponse
from web.forms.project import ProjectCreateModelForm,ProjectCreateForm

def project_list(request):
    if request.method == "GET":
        # request.tracer.project = models.ProjectInfo.objects.filter(id=0).first()
        print(request.tracer.price_policy,request.tracer.user,"看这里--------------------",__name__)
        form = ProjectCreateModelForm(request)
        project_dict = {"star":[],"my":[],"join":[]}
        # 获取当前用户创建的项目
        my_project_object = models.ProjectInfo.objects.filter(create_user=request.tracer.user)
        for row in my_project_object:
            if row.star_flag:
                project_dict["star"].append({"value":row,"type":"my"})
            else:
                project_dict["my"].append(row)
        # 获取当前用户参与的项目
        join_project_object = models.ParticipatorInfo.objects.filter(participator=request.tracer.user,status=1)
        for item in join_project_object:
            if item.star_flag:
                project_dict["star"].append({"value":item.project,"type":"join"})
            else:
                project_dict["join"].append(item.project)

        return render(request, "project/project_list.html", {"form":form, "project_dict":project_dict})
    # 创建项目
    form = ProjectCreateModelForm(request,data = request.POST)
    if form.is_valid():
        form.instance.create_user = request.tracer.user
        form.instance.used_size = 0
        instance = form.save()
        # 初始化项目问题类型 **************************bulk_create:批量插入
        issues_type_insert_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:
            issues_type_insert_list.append(models.IssuesType(project=instance,title=item))
        models.IssuesType.objects.bulk_create(issues_type_insert_list)
        return JsonResponse({"status":True})
    return JsonResponse({"status":False,"errors":form.errors})

def project_star(request,project_type,project_id):
    print(project_type,project_id)
    if project_type == "my":
        models.ProjectInfo.objects.filter(id=project_id,create_user=request.tracer.user).update(star_flag=True)
    elif project_type == "join":
        models.ParticipatorInfo.objects.filter(project_id=project_id,participator=request.tracer.user).update(star_flag=True)
    else:
        return HttpResponse("请求错误")
    return redirect('project_list')

def project_unstar(request,project_type,project_id):
    print(project_type,project_id)
    if project_type == "my":
        models.ProjectInfo.objects.filter(id=project_id,create_user=request.tracer.user).update(star_flag=False)
    elif project_type == "join":
        models.ParticipatorInfo.objects.filter(project_id=project_id,participator=request.tracer.user).update(star_flag=False)
    else:
        return HttpResponse("请求错误")
    return redirect('project_list')